from odoo import models, fields
import urllib3
import json


class FlowableSettings(models.TransientModel):
    _name = "beet_flowable.settings"
    _description = '流程配置'

    name = fields.Char("名称")

    def sync_users(self):
        records = self.env['res.users'].sudo().search([])
        for record in records:
            # 查找 idm 用户
            if self.is_idm_user(record['id']):
                # 如果存在则更新
                self.update_idm_user(record)
            else:
                self.add_idm_user(record)
                # 如果不存在则添加

        records = self.env['res.groups'].sudo().search([])
        for record in records:
            # 查找 idm 用户
            if self.is_idm_group(record['id']):
                # 如果存在则更新
                self.update_idm_group(record)
            else:
                self.add_idm_group(record)
                # 如果不存在则添加

    def add_idm_user(self, record):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        headers.update({'Content-Type': 'application/json'})
        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/identity/users'
        if record['display_name']:
            if len(record['display_name'].split()) == 2:
                first_name = record['display_name'].split()[0]
                last_name = record['display_name'].split()[1]
            else:
                first_name = last_name = record['display_name']

        data = {
            "id": record['id'],
            "email": record['email'],
            "firstName": first_name,
            "lastName": last_name,
            "displayName": record['display_name'],
            "password": "password"
        }
        postdata = json.dumps(data).encode('utf-8')
        r = http.request('POST', URL, headers=headers, body=postdata)

        return r.status

    def add_idm_group(self, record):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        headers.update({'Content-Type': 'application/json'})
        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/identity/groups'

        data = {
            "id": record['id'],
            "name": record['display_name']
        }
        postdata = json.dumps(data).encode('utf-8')
        r = http.request('POST', URL, headers=headers, body=postdata)

        return r.status

    def update_idm_user(self, record):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        headers.update({'Content-Type': 'application/json'})
        URL = 'http://localhost:8080/flowable-rest/idm-api/users/testuser/%s' % record['id']
        if record['display_name']:
            first_name = record['display_name'].split()[0]
            last_name = record['display_name'].split()[1]
        data = {
            "id": record['id'],
            "email": record['email'],
            "firstName": first_name,
            "lastName": last_name,
            "displayName": record['display_name'],
            "password": "password"
        }
        postdata = json.dumps(data).encode('utf-8')
        r = http.request('PUT', URL, headers=headers, body=postdata)

        return r.status

    def update_idm_group(self, record):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        headers.update({'Content-Type': 'application/json'})
        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/idm-api/groups/%s' % record['id']

        data = {
            "id": record['id'],
            "name": record['display_name']
        }
        postdata = json.dumps(data).encode('utf-8')
        r = http.request('PUT', URL, headers=headers, body=postdata)

        return r.status

    def sync_tasks(self):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/history/historic-task-instances'
        r = http.request('GET', URL, headers=headers)
        if r.status == 200:
            # 更新数据
            data = json.loads(r.data.decode('utf-8'))
            for item in data['data']:
                records = self.env['beet_flowable.task'].sudo().search([('p_id', '=', item['id'])], limit=1)
                if records:
                    records[0].write({'p_id': item['id'], 'name': item['name'], 'url': item['url'], 'end_time': item['endTime']})
                else:
                    self.env['beet_flowable.task'].create(
                        {'p_id': item['id'], 'name': item['name'], 'url': item['url'], 'end_time': item['endTime']})

    def sync_process_definitions(self):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/repository/process-definitions'
        r = http.request('GET', URL, headers=headers)
        if r.status == 200:
            # 更新数据
            data = json.loads(r.data.decode('utf-8'))
            for item in data['data']:
                records = self.env['beet_flowable.process'].sudo().search([('p_id', '=', item['id'])], limit=1)
                url = 'http://rest-admin:test@localhost:8080/flowable-rest/service/runtime/process-instances/%s/diagram' % item['id']
                print(url)
                if records:
                    records[0].write({'p_id': item['id'], 'name': item['name'], 'url': url})
                else:
                    self.env['beet_flowable.process'].create({'p_id': item['id'], 'name': item['name'], 'url': url})

    def is_idm_user(self, user_id):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        URL = 'http://localhost:8080/flowable-rest/service/identity/users/%s' % user_id
        r = http.request('GET', URL, headers=headers)
        if r.status == 200:
            return True
        else:
            return False

    def is_idm_group(self, group_id):
        http = urllib3.PoolManager()
        headers = urllib3.util.make_headers(basic_auth='rest-admin:test')
        URL = 'http://rest-admin:test@localhost:8080/flowable-rest/service/identity/groups/%s' % group_id
        r = http.request('GET', URL, headers=headers)
        if r.status == 200:
            return True
        else:
            return False
